<?php

	//не может сужествовать объектов этого класса
	abstract class OwnedObject extends ModelObject{
		protected $modelName = 'Owned';
		protected $owner = null;

		public static function Install() {
                ModelObject::Install();

				//TODO проверить наличие поля Owner в таблице Object

				$query = sprintf("ALTER TABLE `Object` ADD `Owner` INT( 32 )");
				mysql_query($query);

				$query=sprintf("ALTER TABLE `Object` ADD CONSTRAINT FK_USER FOREIGN KEY ( Owner ) REFERENCES User( Id )");
				mysql_query($query);

				echo "Owned object installed\n";
		}

		public function AsSource($otherName = false){
			$res = parent::AsSource($otherName);
			$res->Attribute('owner',$this->owner);
			return $res;
		}

		protected function RegisterObject() {
			//Авторизирован ли пользователь
			if($_SESSION['userid']<1) throw new Exception("No authorized user.");
			$this->owner = $_SESSION['userid'];

			$obj_id = parent::RegisterObject();

			$query = sprintf("UPDATE `Object` SET Owner = %d WHERE `id`=%d",$this->owner,$obj_id);
			mysql_query($query);

			return $obj_id;
		}

		public function Load() {
			if($this->id<1) throw new Exception("Can't load object because it's id isn't defined");
			$query = sprintf("SELECT `created`, `Owner` FROM `Object` WHERE `id`=%d", intval($this->id));
			$res = mysql_query($query);
			if($res) {
				$row = mysql_fetch_assoc($res);
				$this->created = $row['created'];
				$this->owner = $row['Owner'];
			}else{
				throw new Exception("Can't load object with SQL error!");
			}
		}

		public function Owner($newOwer=false) {
					if($newOwner)
							$this->owner = $newOwner;
					return $this->owner;
		}

        public function IsOwner($user){
             if($user instanceof User) 
                   return $user->Id() == $this->owner;
             else throw new Exception("Invalid argument User instance required");
        }
          
        public function CanEdit($user = false){
        	if(!$user){
        		if($_SESSION['userid']<1) throw new Exception("No authorized user.");
        		$user = new User($_SESSION['userid']);
        		$user->Load();
        	}
   		    return  $this->IsOwner($user) || $user->Status() == USER_STATUS_ADMIN;
        }

	}
?>
